#include "form.h"
#include "ui_form.h"
#include <QDebug>
#include <QTableWidgetItem>
#include <QTcpSocket>
#include <QHostAddress>
#include <QSqlDatabase>
#include <QSqlQuery>
#include <QSqlError>
#include <QFile>

Form::Form(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::Form),
    socket(new QTcpSocket(this))
{
    ui->setupUi(this);

    // 初始化表格控件
    initializeTable();

    // 配置 TCP 客户端
    socket->connectToHost("192.168.50.107", 8080);

    // 连接信号和槽
    connect(socket, &QTcpSocket::connected, this, &Form::onConnected);
    connect(socket, &QTcpSocket::disconnected, this, &Form::onDisconnected);
    connect(socket, &QTcpSocket::readyRead, this, &Form::onReadyRead);

    // 直接加载数据到表格
    loadDataDirectly();
}

Form::~Form()
{
    delete ui;
}

void Form::initializeTable()
{
    // 设置表格的基本属性
    ui->tableWidget->setColumnCount(5); // 设置列数为5
    ui->tableWidget->setHorizontalHeaderLabels({"住户", "温度℃", "湿度%", "电路", "时间"}); // 设置表头
    ui->tableWidget->setColumnWidth(0, 70);
    ui->tableWidget->setColumnWidth(1, 90);
    ui->tableWidget->setColumnWidth(2, 90);
    ui->tableWidget->setColumnWidth(3, 80);
    ui->tableWidget->setColumnWidth(4, 120);

    // 禁用表格的编辑功能
    ui->tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);

    // 设置点击单元格时高亮整行
    ui->tableWidget->setStyleSheet(
        "QTableWidget::item:selected {"
        "background-color: #00008B;" // 设置高亮颜色
        "}"
    );

    connect(ui->tableWidget, &QTableWidget::cellClicked, [this](int row, int column) {
        ui->tableWidget->selectRow(row); // 点击单元格时高亮整行
    });
}

void Form::loadDataDirectly()
{
    // 定义要插入的数据
    QList<QStringList> data = {
        {"1", "2", "1", "1", "1"}, // 示例数据
        {"201", "22", "50", "正常", "2024.1.1 12:00"},
        {"301", "25", "60", "异常", "2024.1.2 13:00"}
    };

    // 清空表格（如果需要）
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    // 插入数据到表格
    for (const QStringList &rowData : data) {
        if (rowData.size() == 5) { // 确保每行有5个字段
            int row = ui->tableWidget->rowCount();
            ui->tableWidget->insertRow(row); // 插入新行
            for (int col = 0; col < rowData.size(); ++col) {
                QTableWidgetItem *item = new QTableWidgetItem(rowData[col]);
                ui->tableWidget->setItem(row, col, item);
                qDebug() << "Inserted item:" << rowData[col] << "at row:" << row << "column:" << col;
            }
        }
    }

    qDebug() << "Data loaded into table.";
    qDebug() << "Number of rows in table:" << ui->tableWidget->rowCount();
}

void Form::onConnected()
{
    qDebug() << "Connected to server.";
}

void Form::onDisconnected()
{
    qDebug() << "Disconnected from server.";
}

void Form::onReadyRead()
{
    QByteArray buffer = socket->readAll();
    qDebug() << "Received data from server:" << buffer;

    // 保存接收到的数据库文件
    QString filePath = "/tmp/database.db";
    QFile file(filePath);
    if (file.open(QIODevice::WriteOnly)) {
        file.write(buffer);
        file.close();
        qDebug() << "Database file saved to:" << filePath;
        loadDatabaseFile(filePath);
    } else {
        qDebug() << "Failed to save database file.";
    }
}

void Form::loadDatabaseFile(const QString &filePath)
{
    // 加载数据库文件
    db = QSqlDatabase::addDatabase("QSQLITE");
    db.setDatabaseName(filePath);

    if (!db.open()) {
        qDebug() << "Error opening database:" << db.lastError().text();
        return;
    }

    QSqlQuery query(db);
    if (!query.exec("SELECT * FROM your_table_name")) { // 替换为你的表名
        qDebug() << "Error executing query:" << query.lastError().text();
        return;
    }

    // 清空表格（如果需要）
    ui->tableWidget->clearContents();
    ui->tableWidget->setRowCount(0);

    // 插入数据到表格
    while (query.next()) {
        int row = ui->tableWidget->rowCount();
        ui->tableWidget->insertRow(row); // 插入新行
        ui->tableWidget->setItem(row, 0, new QTableWidgetItem(query.value(0).toString())); // 住户
        ui->tableWidget->setItem(row, 1, new QTableWidgetItem(query.value(1).toString())); // 温度
        ui->tableWidget->setItem(row, 2, new QTableWidgetItem(query.value(2).toString())); // 湿度
        ui->tableWidget->setItem(row, 3, new QTableWidgetItem(query.value(3).toString())); // 电路
        ui->tableWidget->setItem(row, 4, new QTableWidgetItem(query.value(4).toString())); // 时间
    }

    qDebug() << "Data loaded from database into table.";
    qDebug() << "Number of rows in table:" << ui->tableWidget->rowCount();
}
